package com.hskn.hss.app.tlemergentplan.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hskn.hss.app.tlemergentplan.service.APPITlEmergentPlanService;
import com.hskn.hss.core.annotation.DataScope;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.utils.LoginUtils;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.cases.entity.Cases;
import com.hskn.hss.module.depart.entity.SysDepart;
import com.hskn.hss.module.depart.mapper.SysDepartMapper;
import com.hskn.hss.module.depart.service.ISysDepartService;
import com.hskn.hss.module.grid.entity.Grid;
import com.hskn.hss.module.grid.service.IGridService;
import com.hskn.hss.module.role.entity.SysRole;
import com.hskn.hss.module.role.mapper.SysRoleMapper;
import com.hskn.hss.module.tlcar.entity.TlCar;
import com.hskn.hss.module.tlcar.mapper.TlCarMapper;
import com.hskn.hss.module.tlcar.service.ITlCarService;
import com.hskn.hss.module.tlcartype.entity.TlCarType;
import com.hskn.hss.module.tlcartype.mapper.TlCarTypeMapper;
import com.hskn.hss.module.tlcartype.service.ITlCarTypeService;
import com.hskn.hss.module.tldictlevel.entity.TlEmergentDictLevel;
import com.hskn.hss.module.tldictlevel.service.ITlEmergentDictLevelService;
import com.hskn.hss.module.tldicttype.entity.TlEmergentDictType;
import com.hskn.hss.module.tldicttype.mapper.TlEmergentDictTypeMapper;
import com.hskn.hss.module.tlemergentcar.entity.TlEmergentPlanCar;
import com.hskn.hss.module.tlemergentcar.mapper.TlEmergentPlanCarMapper;
import com.hskn.hss.module.tlemergentcar.service.ITlEmergentPlanCarService;
import com.hskn.hss.module.tlemergentemp.entity.TlEmergentPlanEmp;
import com.hskn.hss.module.tlemergentemp.mapper.TlEmergentPlanEmpMapper;
import com.hskn.hss.module.tlemergentemp.service.ITlEmergentPlanEmpService;
import com.hskn.hss.module.tlemergentopera.entity.TlEmergentPlanOperadetails;
import com.hskn.hss.module.tlemergentopera.mapper.TlEmergentPlanOperadetailsMapper;
import com.hskn.hss.module.tlemergentopera.service.ITlEmergentPlanOperadetailsService;
import com.hskn.hss.module.tlemergentplan.entity.TlEmergentPlan;
import com.hskn.hss.module.tlemergentplan.mapper.TlEmergentPlanMapper;
import com.hskn.hss.module.tlemergentplan.vo.*;
import com.hskn.hss.module.tlemployee.entity.TlEmployee;
import com.hskn.hss.module.tlemployee.service.ITlEmployeeService;
import com.hskn.hss.module.tlresplan.entity.TlEmergentResplan;
import com.hskn.hss.module.tlresplan.mapper.TlEmergentResplanMapper;
import com.hskn.hss.module.tlworktype.entity.TlWorkType;
import com.hskn.hss.module.tlworktype.mapper.TlWorkTypeMapper;
import com.hskn.hss.module.tlworktype.service.ITlWorkTypeService;
import com.hskn.hss.module.user.entity.User;
import com.hskn.hss.module.user.mapper.UserMapper;
import com.hskn.hss.module.user.service.IUserService;
import com.hskn.hss.module.userdepart.entity.SysUserDepart;
import com.hskn.hss.module.userdepart.mapper.SysUserDepartMapper;
import com.hskn.hss.module.userrole.entity.SysUserRole;
import com.hskn.hss.module.userrole.mapper.SysUserRoleMapper;
import com.hskn.hss.utils.AttributeUtils;
import com.hskn.hss.utils.GroupingByUtils;
import com.hskn.hss.utils.StringUtils;
import com.hskn.hss.utils.WebSocketUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2021-05-18
 */
@Service
public class APPTlEmergentPlanServiceImpl extends ServiceImpl<TlEmergentPlanMapper, TlEmergentPlan> implements APPITlEmergentPlanService {

    @Resource
    TlEmergentPlanMapper tlEmergentPlanMapper;
    @Resource
    TlCarMapper tlCarMapper;
    @Resource
    SysDepartMapper sysDepartMapper;
    @Resource
    SysUserDepartMapper sysUserDepartMapper;
    @Autowired
    ITlEmergentPlanCarService tlEmergentPlanCarService;
    @Autowired
    ITlEmergentPlanEmpService tlEmergentPlanEmpService;
    @Autowired
    ITlEmergentPlanOperadetailsService tlEmergentPlanOperadetailsService;
    @Resource
    TlEmergentPlanCarMapper tlEmergentPlanCarMapper;
    @Resource
    TlEmergentPlanEmpMapper tlEmergentPlanEmpMapper;
    @Resource
    TlEmergentPlanOperadetailsMapper tlEmergentPlanOperadetailsMapper;
    @Resource
    TlEmergentResplanMapper tlEmergentResplanMapper;
    @Resource
    TlEmergentDictTypeMapper tlEmergentDictTypeMapper;
    @Autowired
    ITlEmergentDictLevelService tlEmergentDictLevelService;
    @Autowired
    IGridService iGridService;
    @Autowired
    IUserService iUserService;
    @Resource
    UserMapper userMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Autowired
    ITlCarTypeService tlCarTypeService;
    @Autowired
    ITlWorkTypeService tlWorkTypeService;
    @Autowired
    ITlCarService tlCarService;
    @Autowired
    ITlEmployeeService tlEmployeeService;
    @Autowired
    ISysDepartService sysDepartService;

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class}) //添加事务
    public AjaxResult insert(TlEmergentPlan tlEmergentPlan) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserDepart::getUserid, uid);
        String deptid = sysUserDepartMapper.selectOne(queryWrapper).getDepid();
        tlEmergentPlan.setCreateby(uid);
        tlEmergentPlan.setCreatetime(new Date());
        tlEmergentPlan.setDeptid(deptid);
        tlEmergentPlanMapper.insert(tlEmergentPlan);
        String askcar = "";
        String askemp = "";

        Map<String, SysDepart> departMap = sysDepartService.getDepartMap(new QueryWrapper<>());
        Map<String, TlCar> carMap = tlCarService.getCarMap(new QueryWrapper<>());
        Map<String, TlEmployee> employeeMap = tlEmployeeService.getEmpMap(new QueryWrapper<>());
        Map<String, TlCarType> carTypeMap = tlCarTypeService.getCarTypeMap(new QueryWrapper<>());
        Map<String, TlWorkType> tlWorkTypeMap = tlWorkTypeService.getTlWorkTypeMap(new QueryWrapper<>());

        List<TlEmergentPlanCar> cars = tlEmergentPlan.getCardetails();
        if (null != cars && cars.size() > 0) {
            for (TlEmergentPlanCar car : cars) {
                car.setPlanid(tlEmergentPlan.getId());
                askcar += car.getCarname() + ",";
                TlCar tlCar = carMap.get(car.getCarid());
                if (Objects.nonNull(tlCar)){
                    SysDepart sysDepart = departMap.get(tlCar.getCardeptid());
                    if (Objects.nonNull(sysDepart)){
                        car.setDepartid(sysDepart.getId());
                        car.setDepartname(sysDepart.getDepartName());
                    }
                    TlCarType tlCarType = carTypeMap.get(tlCar.getCartypeid());
                    if (Objects.nonNull(tlCarType)){
                        car.setCartype(tlCarType.getTypename());
                    }
                    tlEmergentPlanCarService.insert(car);
                }
            }
        }

        List<TlEmergentPlanEmp> emps = tlEmergentPlan.getEmpdetails();
        if (null != emps && emps.size() > 0) {
            for (TlEmergentPlanEmp emp : emps) {
                emp.setPlanid(tlEmergentPlan.getId());
                askemp += emp.getEmpname() + ",";
                TlEmployee tlEmployee = employeeMap.get(emp.getEmpid());
                if (Objects.nonNull(tlEmployee)){
                    SysDepart sysDepart = departMap.get(tlEmployee.getDeptid());
                    if (Objects.nonNull(sysDepart)){
                        emp.setDepartid(sysDepart.getId());
                        emp.setDepartname(sysDepart.getDepartName());
                    }
                    TlCarType tlCarType = carTypeMap.get(tlEmployee.getWorktype());
                    if (Objects.nonNull(tlCarType)){
                        emp.setEmptype(tlCarType.getTypename());
                    }
                    tlEmergentPlanEmpService.insert(emp);
                }
            }
        }

        tlEmergentPlan.setAskcar(askcar);
        tlEmergentPlan.setAskemp(askemp);
        tlEmergentPlanMapper.updateById(tlEmergentPlan);

        TlEmergentPlanOperadetails tlEmergentPlanOperadetails = new TlEmergentPlanOperadetails();
        tlEmergentPlanOperadetails.setPlanid(tlEmergentPlan.getId());
        tlEmergentPlanOperadetails.setStatus("0");  //新增操作
        tlEmergentPlanOperadetails.setOperatime(new Date());
        tlEmergentPlanOperadetails.setRemark(tlEmergentPlan.getDetail());
        tlEmergentPlanOperadetails.setOperator(uid);
        tlEmergentPlanOperadetailsService.insert(tlEmergentPlanOperadetails);

        User user1 = userMapper.selectById(tlEmergentPlan.getDutyperson());
        JSONObject alarmJson = new JSONObject();
        alarmJson.put("model", 6);
        JSONObject detailJson = new JSONObject();
        detailJson.put("id", tlEmergentPlanOperadetails.getId());
        detailJson.put("remindKey", "eventInspectReport");
        detailJson.put("happenTime", DateUtil.formatDateTime(new Date()));
        detailJson.put("lng", tlEmergentPlanOperadetails.getLng());
        detailJson.put("lat", tlEmergentPlanOperadetails.getLat());
        detailJson.put("address", tlEmergentPlanOperadetails.getAddr());
        detailJson.put("pic", tlEmergentPlanOperadetails.getFileurl());
        detailJson.put("planId", tlEmergentPlanOperadetails.getPlanid());
        detailJson.put("authorId", uid);
        detailJson.put("authorName", user1.getAccount());
        detailJson.put("authorType", "tlEmergentPlanOperadetails");
        detailJson.put("personId", tlEmergentPlan.getDutyperson());
        detailJson.put("personName", user1.getName());
        detailJson.put("status", tlEmergentPlanOperadetails.getStatus());
        alarmJson.put("detail", detailJson);
        WebSocketUtils.sendMessageToOne(alarmJson.toString(), tlEmergentPlan.getDutyperson());

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.lambda().notIn(User::getUid, tlEmergentPlan.getDutyperson());
        List<User> userList = userMapper.selectList(userQueryWrapper);

        QueryWrapper<SysUserRole> sysUserRoleQueryWrapper = new QueryWrapper<>();
        List<SysUserRole> sysUserRoleList = sysUserRoleMapper.selectList(sysUserRoleQueryWrapper);
        Map<String, List<SysUserRole>> sysUserRoleMap = sysUserRoleList.stream().collect(Collectors.groupingBy(SysUserRole::getUserid));

        QueryWrapper<SysRole> sysRoleQueryWrapper = new QueryWrapper<>();
        List<SysRole> sysRoleList = sysRoleMapper.selectList(sysRoleQueryWrapper);
        Map<String, SysRole> sysRoleMap = sysRoleList.stream().collect(Collectors.groupingBy(SysRole::getId, Collectors.collectingAndThen(toList(), values -> values.get(0))));
        for (User user : userList) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("model", 6);
            JSONObject object = new JSONObject();
            object.put("id", tlEmergentPlanOperadetails.getId());
            object.put("remindKey", "eventInspectReport");
            object.put("happenTime", DateUtil.formatDateTime(new Date()));
            object.put("lng", tlEmergentPlanOperadetails.getLng());
            object.put("lat", tlEmergentPlanOperadetails.getLat());
            object.put("address", tlEmergentPlanOperadetails.getAddr());
            object.put("pic", tlEmergentPlanOperadetails.getFileurl());
            object.put("planId", tlEmergentPlanOperadetails.getPlanid());
            object.put("authorId", uid);
            object.put("authorName", user.getAccount());
            object.put("authorType", "tlEmergentPlanOperadetails");
            object.put("personId", user.getUid());
            object.put("personName", user.getName());
            object.put("status", tlEmergentPlanOperadetails.getStatus());
            jsonObject.put("detail", detailJson);
            List<SysUserRole> sysUserRoleList1 = sysUserRoleMap.get(user.getUid());
            if (null != sysUserRoleList1) {
                for (SysUserRole sysUserRole : sysUserRoleList1) {
                    SysRole sysRole = sysRoleMap.get(sysUserRole.getRoleid());
                    if (null != sysRole) {
                        if (sysRole.getRoleName().equals("管理员")) {
                            WebSocketUtils.sendMessageToOne(jsonObject.toString(), sysUserRole.getUserid());
                        }
                    }
                }
            }
        }
        return AjaxResult.success("操作成功");
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class}) //添加事务
    public AjaxResult update(TlEmergentPlan tlEmergentPlan) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        tlEmergentPlan.setUpdateby(uid);
        tlEmergentPlan.setUpdatetime(new Date());

        String askcar = "";
        String askemp = "";

        tlEmergentPlanCarService.deletebyid(tlEmergentPlan.getId());
        List<TlEmergentPlanCar> cars = tlEmergentPlan.getCardetails();
        if (null != cars && cars.size() > 0) {
            for (TlEmergentPlanCar car : cars) {
                car.setPlanid(tlEmergentPlan.getId());
                askcar += car.getCarname() + ",";
                TlCar tlCar = tlCarMapper.selectById(car.getCarid());
                SysDepart sysDepart = sysDepartMapper.selectById(tlCar.getCardeptid());
                car.setDepartid(sysDepart.getId());
                car.setDepartname(sysDepart.getDepartName());
                tlEmergentPlanCarService.insert(car);
            }
        }


        tlEmergentPlanEmpService.deletebyid(tlEmergentPlan.getId());
        List<TlEmergentPlanEmp> emps = tlEmergentPlan.getEmpdetails();
        if (null != emps && emps.size() > 0) {
            for (TlEmergentPlanEmp emp : emps) {
                emp.setPlanid(tlEmergentPlan.getId());
                askemp += emp.getEmpname() + ",";
                tlEmergentPlanEmpService.insert(emp);
            }
        }

        tlEmergentPlan.setAskcar(askcar);
        tlEmergentPlan.setAskemp(askemp);
        tlEmergentPlanMapper.updateById(tlEmergentPlan);

        TlEmergentPlanOperadetails tlEmergentPlanOperadetails = new TlEmergentPlanOperadetails();
        tlEmergentPlanOperadetails.setPlanid(tlEmergentPlan.getId());
        tlEmergentPlanOperadetails.setStatus("2"); //修改操作
        tlEmergentPlanOperadetails.setOperatime(new Date());
        tlEmergentPlanOperadetails.setRemark("应急计划已修改");
        tlEmergentPlanOperadetails.setOperator(uid);
        tlEmergentPlanOperadetailsService.insert(tlEmergentPlanOperadetails);

        return AjaxResult.success("操作成功");

    }

    @Override
    @Transactional
    public AjaxResult audit(TlEmergentPlanOperadetails tlEmergentPlanOperadetails) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        String planid = tlEmergentPlanOperadetails.getPlanid();
        String lat = tlEmergentPlanOperadetails.getLat();
        String lng = tlEmergentPlanOperadetails.getLng();
        String addr = tlEmergentPlanOperadetails.getAddr();
        String status = tlEmergentPlanOperadetails.getStatus();
        String remark = tlEmergentPlanOperadetails.getRemark();
        String fileurl = tlEmergentPlanOperadetails.getFileurl();
        String ids = tlEmergentPlanOperadetails.getIds();
        String[] idArray = ids.split(",");
        QueryWrapper<TlEmergentPlan> tlEmergentPlanQueryWrapper = new QueryWrapper<>();
        tlEmergentPlanQueryWrapper.lambda().in(TlEmergentPlan::getId, idArray);
        List<TlEmergentPlan> tlEmergentPlanList = tlEmergentPlanMapper.selectList(tlEmergentPlanQueryWrapper);
        for (TlEmergentPlan tlEmergentPlan : tlEmergentPlanList) {
            tlEmergentPlan.setStatus(status);
            tlEmergentPlanMapper.updateById(tlEmergentPlan);
            Date starttime = tlEmergentPlan.getCreatetime();
            Long second = (new Date().getTime() - starttime.getTime()) / 1000;

            long day1 = second / (24 * 3600);
            long hour1 = second % (24 * 3600) / 3600;
            long minute1 = second % 3600 / 60;
            long second1 = second % 60 / 60;


            TlEmergentPlanOperadetails ttlEmergentPlanOperadetails = new TlEmergentPlanOperadetails();
            ttlEmergentPlanOperadetails.setPlanid(tlEmergentPlan.getId());
            ttlEmergentPlanOperadetails.setStatus(status); //修改操作
            ttlEmergentPlanOperadetails.setOperatime(new Date());
            ttlEmergentPlanOperadetails.setRemark(remark);
            ttlEmergentPlanOperadetails.setOperator(uid);
            ttlEmergentPlanOperadetails.setLat(lat);
            ttlEmergentPlanOperadetails.setLng(lng);
            ttlEmergentPlanOperadetails.setAddr(addr);
            ttlEmergentPlanOperadetails.setCosttime(second);
            ttlEmergentPlanOperadetails.setFileurl(fileurl);
            ttlEmergentPlanOperadetails.setCosttimedetail(day1 + "天" + hour1 + "小时" + minute1 + "分" + second1 + "秒");

            tlEmergentPlanOperadetailsService.insert(ttlEmergentPlanOperadetails);
        }

        return AjaxResult.success("操作成功");

    }

    @Override
    @Transactional
    public AjaxResult deletebyid(TlEmergentPlan tlEmergentPlan) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        String id = tlEmergentPlan.getId();
        tlEmergentPlanCarService.deletebyid(id);
        tlEmergentPlanEmpService.deletebyid(id);
        tlEmergentPlanMapper.deleteById(id);

        TlEmergentPlanOperadetails tlEmergentPlanOperadetails = new TlEmergentPlanOperadetails();
        tlEmergentPlanOperadetails.setPlanid(id);
        tlEmergentPlanOperadetails.setStatus("2"); //修改操作
        tlEmergentPlanOperadetails.setOperatime(new Date());
        tlEmergentPlanOperadetails.setRemark("应急计划已删除");
        tlEmergentPlanOperadetails.setOperator(uid);
        tlEmergentPlanOperadetailsService.insert(tlEmergentPlanOperadetails);
        return AjaxResult.success("操作成功");
    }

    @Override
    @Transactional
    public AjaxResult deletebatchbyid(TlEmergentPlan tlEmergentPlan) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        String ids = tlEmergentPlan.getIds();
        String[] idArray = ids.split(",");
        tlEmergentPlanMapper.deleteBatchIds(Arrays.asList(idArray));

        for (String id :
                idArray) {
            tlEmergentPlanCarService.deletebyid(id);
            tlEmergentPlanEmpService.deletebyid(id);
            TlEmergentPlanOperadetails tlEmergentPlanOperadetails = new TlEmergentPlanOperadetails();
            tlEmergentPlanOperadetails.setPlanid(id);
            tlEmergentPlanOperadetails.setStatus("2"); //修改操作
            tlEmergentPlanOperadetails.setOperatime(new Date());
            tlEmergentPlanOperadetails.setRemark("应急计划已删除");
            tlEmergentPlanOperadetails.setOperator(uid);
            tlEmergentPlanOperadetailsService.insert(tlEmergentPlanOperadetails);
        }

        return AjaxResult.success("操作成功");
    }

    @Override
    public AjaxResult changeStatus(TlEmergentPlan tlEmergentPlan) throws HssException {

        String username = LoginUtils.getUser().getAccount();
        String ids = tlEmergentPlan.getIds();
        String[] idArray = ids.split(",");
        tlEmergentPlan.setUpdateby(username);
        tlEmergentPlan.setUpdatetime(new Date());

        UpdateWrapper<TlEmergentPlan> tlEmergentPlanUpdateWrapper = new UpdateWrapper<>();
        tlEmergentPlanUpdateWrapper.lambda().in(TlEmergentPlan::getId, idArray);

        int i = tlEmergentPlanMapper.update(tlEmergentPlan, tlEmergentPlanUpdateWrapper);

        boolean flag = i > 0 ? true : false;
        if (flag) {
            return AjaxResult.success("操作成功");
        } else {
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @Override
    public TlEmergentPlan getDetail(TlEmergentPlan tlEmergentPlan) throws HssException {

        String id = tlEmergentPlan.getId();
        Map<String, Grid> gridCollect = iGridService.list().stream().collect(Collectors.groupingBy(Grid::getGridId, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0))));
        Map<String, User> userCollect = iUserService.list().stream().collect(Collectors.groupingBy(User::getUid, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0))));

        tlEmergentPlan = tlEmergentPlanMapper.selectById(id);

        calculationsAndDetails(tlEmergentPlan);
        if (null != gridCollect.get(tlEmergentPlan.getGridId())) {
            tlEmergentPlan.setGridname(gridCollect.get(tlEmergentPlan.getGridId()).getName());
        }
        if (null != userCollect.get(tlEmergentPlan.getDutyperson())) {
            tlEmergentPlan.setDutypersonname(userCollect.get(tlEmergentPlan.getDutyperson()).getName());
        }

        return tlEmergentPlan;
    }

    @Override
    public List getSelectList(TlEmergentPlan tlEmergentPlan) {
        Map<String, Object> map = new HashMap();
        map.put("status", tlEmergentPlan.getStatus());
        List resultList = tlEmergentPlanMapper.getSelectList(map);
        return resultList;
    }

    @Override
    @DataScope(deptAlias = "deptid", userAlias = "dutyperson, createby")
    public TlEmergentPlanVO getList(TlEmergentPlan tlEmergentPlan) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        Long page = StringUtils.isEmpty(tlEmergentPlan.getPage()) ? 1 : tlEmergentPlan.getPage();
        Long size = StringUtils.isEmpty(tlEmergentPlan.getSize()) ? 10 : tlEmergentPlan.getSize();

        Map<String, Grid> gridCollect = iGridService.list().stream().collect(Collectors.groupingBy(Grid::getGridId, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0))));
        Map<String, User> userCollect = iUserService.list().stream().collect(Collectors.groupingBy(User::getAccount, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0))));
        QueryWrapper<TlEmergentResplan> tlEmergentResplanQueryWrapper = new QueryWrapper<>();
        List<TlEmergentResplan> tlEmergentResplanList = tlEmergentResplanMapper.selectList(tlEmergentResplanQueryWrapper);
        Map<String, TlEmergentResplan> tlEmergentResplanMap = GroupingByUtils.getGroupingForMapEntity(tlEmergentResplanList, TlEmergentResplan::getId, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        Map<String, List<TlEmergentResplan>> tlEmergentResplanMapByLevel = tlEmergentResplanList.stream().collect(Collectors.groupingBy(TlEmergentResplan::getEmergentlevelid));
        List resplanlist = new ArrayList();
        if (tlEmergentResplanMapByLevel.containsKey(tlEmergentPlan.getLevelId())) {
            List<TlEmergentResplan> emergentResplanList = tlEmergentResplanMapByLevel.get(tlEmergentPlan.getLevelId());
            emergentResplanList.forEach(Resplan -> {
                resplanlist.add(Resplan.getId());
            });
        }

        QueryWrapper<TlEmergentDictType> tlEmergentDictTypeQueryWrapper = new QueryWrapper<>();
        List<TlEmergentDictType> tlEmergentDictTypeList = tlEmergentDictTypeMapper.selectList(tlEmergentDictTypeQueryWrapper);
        Map<String, TlEmergentDictType> tlEmergentDictTypeMapById = GroupingByUtils.getGroupingForMapEntity(tlEmergentDictTypeList, TlEmergentDictType::getId, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        List<TlEmergentDictLevel> tlEmergentDictLevelList = tlEmergentDictLevelService.list();
        Map<String, TlEmergentDictLevel> tlEmergentDictLevelMapById = GroupingByUtils.getGroupingForMapEntity(tlEmergentDictLevelList, TlEmergentDictLevel::getId, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        Page<TlEmergentPlan> listPage = new Page<>(page, size, true);
        QueryWrapper<TlEmergentPlan> tlEmergentPlanQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(tlEmergentPlan.getDeptid())) {
            tlEmergentPlanQueryWrapper.lambda().eq(TlEmergentPlan::getDeptid, tlEmergentPlan.getDeptid());
        }
        if (StringUtils.isNotEmpty(tlEmergentPlan.getPlanname())) {
            tlEmergentPlanQueryWrapper.lambda().eq(TlEmergentPlan::getPlanname, tlEmergentPlan.getPlanname());
        }
        if (StringUtils.isNotEmpty(tlEmergentPlan.getId())) {
            tlEmergentPlanQueryWrapper.lambda().eq(TlEmergentPlan::getId, tlEmergentPlan.getId());
        }
        if (StringUtils.isNotEmpty(tlEmergentPlan.getStatus())) {
            tlEmergentPlanQueryWrapper.lambda().eq(TlEmergentPlan::getStatus, tlEmergentPlan.getStatus());
        }
        if (StringUtils.isNotEmpty(tlEmergentPlan.getStarttime()) && tlEmergentPlan.getStarttime() != null && StringUtils.isNotEmpty(tlEmergentPlan.getEndtime()) && tlEmergentPlan.getEndtime() != null) {
            tlEmergentPlanQueryWrapper.lambda().between(TlEmergentPlan::getCreatetime, AttributeUtils.timeCompletion(tlEmergentPlan.getStarttime(), 's'), AttributeUtils.timeCompletion(tlEmergentPlan.getEndtime(), 'e'));
        }
        if (null != resplanlist && !resplanlist.isEmpty()) {
            tlEmergentPlanQueryWrapper.lambda().in(TlEmergentPlan::getResplan, resplanlist);
        }

        tlEmergentPlanQueryWrapper.lambda().eq(TlEmergentPlan::getDutyperson, uid);

        IPage<TlEmergentPlan> iPage = tlEmergentPlanMapper.selectPage(listPage, tlEmergentPlanQueryWrapper);


        List<TlEmergentPlan> tlEmergentPlanList = iPage.getRecords();
        if (null != tlEmergentPlanList && !tlEmergentPlanList.isEmpty()) {
            tlEmergentPlanList.forEach(t -> {
                if (null != tlEmergentResplanMap.get(t.getResplan())) {
                    t.setResplanname(tlEmergentResplanMap.get(t.getResplan()).getResplanname());
                    t.setRespondtime(tlEmergentResplanMap.get(t.getResplan()).getRespondtime());
                    t.setDealtime(tlEmergentResplanMap.get(t.getResplan()).getDealtime());
                    t.setRespondtime(tlEmergentResplanMap.get(t.getResplan()).getRespondtime());
                    t.setDealtime(tlEmergentResplanMap.get(t.getResplan()).getDealtime());
                    t.setEmergenttype(tlEmergentDictTypeMapById.get(tlEmergentResplanMap.get(t.getResplan()).getEmergenttypeid()).getEventtype());
                    t.setResplanlevel(tlEmergentDictLevelMapById.get(tlEmergentResplanMap.get(t.getResplan()).getEmergentlevelid()).getLevel());
                }


                if (null != gridCollect.get(t.getGridId())) {
                    t.setGridname(gridCollect.get(t.getGridId()).getName());
                }
                if (null != userCollect.get(t.getDutyperson())) {
                    t.setDutypersonname(userCollect.get(t.getDutyperson()).getName());
                }

            });
        }

        TlEmergentPlanVO tlEmergentPlanVO = new TlEmergentPlanVO();
        tlEmergentPlanVO.setSize(iPage.getSize());
        tlEmergentPlanVO.setPage(iPage.getPages());
        tlEmergentPlanVO.setTotal(iPage.getTotal());
        tlEmergentPlanVO.setCurrent(iPage.getCurrent());
        tlEmergentPlanVO.setTlEmergentPlanList(tlEmergentPlanList);
        return tlEmergentPlanVO;
    }


    @Override
    public List<EmergentPlanVO> emergentPlan() throws HssException {
        List<EmergentPlanVO> emergentPlanVOList = new ArrayList<>();

        /********* 数据准备1 *********/
        // 查询进行中的所有计划

        String date = DateUtil.formatDate(new Date());

        Map map = new HashMap();
        if (StringUtils.isNotEmpty(date)) {
            String startDate = AttributeUtils.timeCompletion(date, 's');
            String endDate = AttributeUtils.timeCompletion(date, 'e');

            map.put("startDate", startDate);
            map.put("endDate", endDate);
        }

        List<TlEmergentPlan> tlEmergentPlanList = tlEmergentPlanMapper.getPlanList(map);

        QueryWrapper<TlEmergentDictType> tlEmergentDictTypeQueryWrapper = new QueryWrapper<>();
        List<TlEmergentDictType> tlEmergentDictTypeList = tlEmergentDictTypeMapper.selectList(tlEmergentDictTypeQueryWrapper);
        Map<String, List<TlEmergentDictType>> tlEmergentDictTypeMapById = tlEmergentDictTypeList.stream().collect(Collectors.groupingBy(TlEmergentDictType::getId));

        // 查询所有预案
        QueryWrapper<TlEmergentResplan> tlEmergentResplanWrapper = new QueryWrapper<>();
        List<TlEmergentResplan> tlEmergentResplanList = tlEmergentResplanMapper.selectList(tlEmergentResplanWrapper);
        Map<String, List<TlEmergentResplan>> tlEmergentResplanMap = tlEmergentResplanList.stream().collect(Collectors.groupingBy(TlEmergentResplan::getId));
        Map<String, List<TlEmergentResplan>> tlEmergentResplanMapByType = tlEmergentResplanList.stream().collect(Collectors.groupingBy(TlEmergentResplan::getEmergenttypeid));

        // 装载levelid
        tlEmergentPlanList.forEach(t -> {
            t.setLevelId("");
            if (null != tlEmergentResplanMap.get(t.getResplan())) {
                t.setLevelId(tlEmergentResplanMap.get(t.getResplan()).get(0).getEmergentlevelid());
                t.setResplanname(tlEmergentResplanMap.get(t.getResplan()).get(0).getResplanname());

                tlEmergentResplanMap.get(t.getResplan()).forEach(t2 -> {
                    t.setEmergenttype(tlEmergentDictTypeMapById.get(t2.getEmergenttypeid()).get(0).getEventtype());
                });


            }
        });

        // 根据levelid进行分组
        Map<String, List<TlEmergentPlan>> tlEmergentPlanMapByLevel = tlEmergentPlanList.stream().collect(Collectors.groupingBy(TlEmergentPlan::getLevelId));

        /********* 数据准备2 *********/
        List<TlEmergentPlanCar> tlEmergentPlanCarList = tlEmergentPlanCarService.list();
        List<TlEmergentPlanEmp> tlEmergentPlanEmpList = tlEmergentPlanEmpService.list();
        Map<String, List<TlEmergentPlanCar>> tlEmergentPlanCarMapByPlanId = tlEmergentPlanCarList.stream().collect(Collectors.groupingBy(TlEmergentPlanCar::getPlanid));
        Map<String, List<TlEmergentPlanEmp>> tlEmergentPlanEmpMapByPlanId = tlEmergentPlanEmpList.stream().collect(Collectors.groupingBy(TlEmergentPlanEmp::getPlanid));

        /******** 数据整合 *********/
        // 创建全部
        EmergentPlanVO emergentPlanVO = new EmergentPlanVO();
        emergentPlanVO.setLevelName("全部");
        emergentPlanVO.setLevelCount(0);
        emergentPlanVO.setEmergentPlanList(new ArrayList<>());
        emergentPlanVOList.add(emergentPlanVO);
        Map<String, Grid> gridCollect = iGridService.list().stream().collect(Collectors.groupingBy(Grid::getGridId, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0))));
        // 加入1级2级。。。。。
        List<TlEmergentDictLevel> tlEmergentDictLevels = tlEmergentDictLevelService.list();
        tlEmergentDictLevels.forEach(t -> {
            EmergentPlanVO emergentPlanVO1 = new EmergentPlanVO();
            emergentPlanVO1.setLevelName(t.getLevel());
            emergentPlanVO1.setLevelCount(0);
            emergentPlanVO1.setEmergentPlanList(new ArrayList<>());
            if (null != tlEmergentPlanMapByLevel.get(t.getId())) {
                emergentPlanVO1.setLevelCount(tlEmergentPlanMapByLevel.get(t.getId()).size());
                emergentPlanVO.setLevelCount(emergentPlanVO.getLevelCount() + tlEmergentPlanMapByLevel.get(t.getId()).size());
                tlEmergentPlanMapByLevel.get(t.getId()).forEach(t1 -> {

                    PlanDetailVO planDetailVO = new PlanDetailVO();
                    planDetailVO.setId(t1.getId());
                    planDetailVO.setLevelName(t.getLevel());
                    planDetailVO.setCreateTime(t1.getCreatetime());
                    planDetailVO.setWorkPlaceDetail(t1.getWorkplacedetail());
                    planDetailVO.setJpgFileUrl(t1.getJpgfileurl());
                    planDetailVO.setEventType(t1.getEmergenttype());
                    planDetailVO.setStatus(t1.getStatusname());
                    planDetailVO.setDutyPerson(t1.getDutyperson());
                    planDetailVO.setWorkPlaceLat(t1.getWorkplacelat());
                    planDetailVO.setWorkPlaceLon(t1.getWorkplacelon());
                    planDetailVO.setPlanName(t1.getPlanname());
                    planDetailVO.setResPlanName(t1.getResplanname());
                    if (null != t1.getGridId()) {
                        Grid grid = gridCollect.get(t1.getGridId());
                        if (null != grid) {
                            planDetailVO.setGrid(grid);
                        }
                    }
                    planDetailVO.setAskEmpCount(0);
                    planDetailVO.setEmergentPlanCarList(new ArrayList<>());
                    planDetailVO.setEmergentPlanPersonList(new ArrayList<>());
                    Date now = new Date();

                    long resPlanTime = now.getTime() - t1.getCreatetime().getTime();
                    long day = resPlanTime / (24 * 60 * 60 * 1000);
                    long hour = (resPlanTime / (60 * 60 * 1000) - day * 24);
                    long min = ((resPlanTime / (60 * 1000)) - day * 24 * 60 - hour * 60);
                    long s = (resPlanTime / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
                    String str = s + "秒";
                    if (day != 0) {
                        str = day + "天" + hour + "小时" + min + "分" + s + "秒";
                    } else if (hour != 0) {
                        str = hour + "小时" + min + "分" + s + "秒";
                    } else if (min != 0) {
                        str = min + "分" + s + "秒";
                    } else {
                        str = s + "秒";
                    }
                    planDetailVO.setResPlanTime(str);
                    // 装载人车
                    if (null != tlEmergentPlanCarMapByPlanId.get(t1.getId())) {
                        tlEmergentPlanCarMapByPlanId.get(t1.getId()).forEach(t2 -> {
                            EmergentPlanCarVO emergentPlanCarVO = new EmergentPlanCarVO();
                            emergentPlanCarVO.setDepartName(t2.getDepartname());
                            emergentPlanCarVO.setCarName(t2.getCarname());
                            emergentPlanCarVO.setCarType(t2.getCartype());
                            planDetailVO.getEmergentPlanCarList().add(emergentPlanCarVO);
                        });
                    }
                    planDetailVO.setAskCarCount(planDetailVO.getEmergentPlanCarList().size());


                    if (null != tlEmergentPlanEmpMapByPlanId.get(t1.getId())) {
                        tlEmergentPlanEmpMapByPlanId.get(t1.getId()).forEach(t2 -> {
                            EmergentPlanPersonVO emergentPlanPersonVO = new EmergentPlanPersonVO();
                            emergentPlanPersonVO.setDepartName(t2.getDepartname());
                            emergentPlanPersonVO.setEmpName(t2.getEmpname());
                            emergentPlanPersonVO.setEmpType(t2.getEmptype());
                            planDetailVO.getEmergentPlanPersonList().add(emergentPlanPersonVO);
                        });
                    }
                    planDetailVO.setAskEmpCount(planDetailVO.getEmergentPlanPersonList().size());

                    emergentPlanVO1.getEmergentPlanList().add(planDetailVO);
                    emergentPlanVO.getEmergentPlanList().add(planDetailVO);

                });
            }

            if (emergentPlanVO1.getLevelCount() > 0) {
                emergentPlanVOList.add(emergentPlanVO1);
            }
        });
        return emergentPlanVOList;


    }


    private void calculationsAndDetails(TlEmergentPlan tlEmergentPlan) {
//        for (TlEmergentPlan tlEmergentPlan : iPage.getRecords()) {
        String id = tlEmergentPlan.getId();

        QueryWrapper<TlEmergentResplan> resqueryWrapper = new QueryWrapper<>();
        resqueryWrapper.lambda().eq(TlEmergentResplan::getId, tlEmergentPlan.getResplan());
        TlEmergentResplan tlEmergentResplan = tlEmergentResplanMapper.selectOne(resqueryWrapper);
        Long minminute = Long.valueOf(tlEmergentResplan.getDealtime());

        QueryWrapper<TlEmergentPlanOperadetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TlEmergentPlanOperadetails::getPlanid, id);
        queryWrapper.lambda().eq(TlEmergentPlanOperadetails::getStatus, "3");
        TlEmergentPlanOperadetails tlEmergentPlanOperadetails = tlEmergentPlanOperadetailsMapper.selectOne(queryWrapper);
        String isover = "";
        if (tlEmergentPlanOperadetails == null) {
            Long second = (new Date().getTime() - tlEmergentPlan.getCreatetime().getTime()) / 1000;
            Long minute = second / 60;
            if (minute > minminute) {
                isover = "逾期";
            } else {
                isover = "未逾期";
            }
        } else {
            Date dealdate = tlEmergentPlanOperadetails.getOperatime();
            Long second = (dealdate.getTime() - tlEmergentPlan.getCreatetime().getTime()) / 1000;
            Long minute = second / 60;
            if (minute > minminute) {
                isover = "逾期";
            } else {
                isover = "未逾期";
            }
        }
        tlEmergentPlan.setIsover(isover);

        /**
         * 获取车辆详情
         */
        List rescarList = new ArrayList();
        Map carmap = new HashMap();
        Map catypemap = new HashMap();
        List<String> cartypelist = tlEmergentPlanCarMapper.gettype();
        for (String type : cartypelist) {
            Map parammap = new HashMap();
            //parammap.put("cartype",type);
            parammap.put("planid", id);
            List carlist = tlEmergentPlanCarMapper.getcarbytype(parammap);
            carmap.put("cartype", type);
            carmap.put("calist", carlist);
        }
        rescarList.add(carmap);
        tlEmergentPlan.setCardetails(rescarList);
        tlEmergentPlan.setCartypes(cartypelist);

        /**
         * 获取 人员详情
         */
        List resempList = new ArrayList();
        Map empmap = new HashMap();
        Map emptypemap = new HashMap();
        List<String> emptypelist = tlEmergentPlanEmpMapper.gettype();
        for (String type : emptypelist) {
            Map parammap = new HashMap();
            //parammap.put("emptype",type);
            parammap.put("planid", id);
            List emplist = tlEmergentPlanEmpMapper.getempbytype(parammap);
            empmap.put("emptype", type);
            empmap.put("emplist", emplist);
        }
        resempList.add(empmap);
        tlEmergentPlan.setEmptypes(emptypelist);
        tlEmergentPlan.setEmpdetails(resempList);
        /**
         * 获取 操作详情
         */
        Map opemap = new HashMap();
        opemap.put("planid", id);
        List<TlEmergentPlanOperadetails> operadetails = tlEmergentPlanOperadetailsMapper.getSelectList(opemap);
        tlEmergentPlan.setOpedetails(operadetails);

//        }
    }
}
